// DOM 加载完成后执行
// 主JavaScript文件 - 包含所有页面共享的功能

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 导航栏滚动效果
    const navbar = document.getElementById('navbar');
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 100) {
                navbar.classList.add('shadow-md');
                navbar.classList.add('bg-white/95');
                navbar.classList.add('backdrop-blur-sm');
            } else {
                navbar.classList.remove('shadow-md');
                navbar.classList.remove('bg-white/95');
                navbar.classList.remove('backdrop-blur-sm');
            }
        });
    }
    
    // 移动端菜单切换
    const mobileMenuBtn = document.getElementById('mobileMenuBtn');
    const mobileMenu = document.getElementById('mobileMenu');
    if (mobileMenuBtn && mobileMenu) {
        mobileMenuBtn.addEventListener('click', function() {
            mobileMenu.classList.toggle('hidden');
            const icon = mobileMenuBtn.querySelector('i');
            if (icon.classList.contains('fa-bars')) {
                icon.classList.remove('fa-bars');
                icon.classList.add('fa-times');
            } else {
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars');
            }
        });
    }
    
    // 搜索框切换
    const searchBtn = document.getElementById('searchBtn');
    const searchBox = document.getElementById('searchBox');
    if (searchBtn && searchBox) {
        searchBtn.addEventListener('click', function() {
            searchBox.classList.toggle('hidden');
            if (!searchBox.classList.contains('hidden')) {
                setTimeout(() => {
                    const searchInput = searchBox.querySelector('input');
                    if (searchInput) searchInput.focus();
                }, 100);
            }
        });
        
        // 点击其他区域关闭搜索框
        document.addEventListener('click', function(event) {
            if (!searchBtn.contains(event.target) && !searchBox.contains(event.target)) {
                searchBox.classList.add('hidden');
            }
        });
    }
    
    // 用户下拉菜单
    const userMenuBtn = document.getElementById('userMenuBtn');
    const userDropdown = document.getElementById('userDropdown');
    if (userMenuBtn && userDropdown) {
        userMenuBtn.addEventListener('click', function() {
            userDropdown.classList.toggle('hidden');
        });
        
        // 点击其他区域关闭下拉菜单
        document.addEventListener('click', function(event) {
            if (!userMenuBtn.contains(event.target) && !userDropdown.contains(event.target)) {
                userDropdown.classList.add('hidden');
            }
        });
    }

    // 轮播图功能
    const carouselItems = document.querySelectorAll('.carousel-item');
    const prevBtn = document.querySelector('.carousel-prev');
    const nextBtn = document.querySelector('.carousel-next');
    const indicators = document.querySelectorAll('.carousel-indicators button');
    let currentSlide = 0;
    let slideInterval;

    if (carouselItems.length > 0) {
        function showSlide(index) {
            // 隐藏所有幻灯片
            carouselItems.forEach(item => {
                item.classList.remove('active');
            });
            // 重置指示器
            indicators.forEach(indicator => {
                indicator.classList.remove('opacity-100');
                indicator.classList.add('opacity-50');
            });

            // 显示当前幻灯片
            carouselItems[index].classList.add('active');
            indicators[index].classList.remove('opacity-50');
            indicators[index].classList.add('opacity-100');
        }

        function nextSlide() {
            currentSlide = (currentSlide + 1) % carouselItems.length;
            showSlide(currentSlide);
        }

        function prevSlide() {
            currentSlide = (currentSlide - 1 + carouselItems.length) % carouselItems.length;
            showSlide(currentSlide);
        }

        // 启动自动轮播
        function startSlideInterval() {
            slideInterval = setInterval(nextSlide, 5000);
        }

        startSlideInterval();

        // 点击事件
        if (prevBtn) prevBtn.addEventListener('click', () => {
            clearInterval(slideInterval);
            prevSlide();
            startSlideInterval();
        });

        if (nextBtn) nextBtn.addEventListener('click', () => {
            clearInterval(slideInterval);
            nextSlide();
            startSlideInterval();
        });

        // 指示器点击
        indicators.forEach((indicator, index) => {
            indicator.addEventListener('click', () => {
                clearInterval(slideInterval);
                currentSlide = index;
                showSlide(currentSlide);
                startSlideInterval();
            });
        });
    }

    // 回到顶部按钮
    const backToTopBtn = document.getElementById('backToTop');
    if (backToTopBtn) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 300) {
                backToTopBtn.classList.remove('opacity-0', 'invisible');
                backToTopBtn.classList.add('opacity-100', 'visible');
            } else {
                backToTopBtn.classList.add('opacity-0', 'invisible');
                backToTopBtn.classList.remove('opacity-100', 'visible');
            }
        });
        
        backToTopBtn.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }
    
    // 活动卡片悬停效果（适用于活动列表页）
    const activityCards = document.querySelectorAll('.activity-card');
    activityCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.classList.add('shadow-lg', '-translate-y-1');
        });
        card.addEventListener('mouseleave', function() {
            this.classList.remove('shadow-lg', '-translate-y-1');
        });
    });
    
    // 数字格式化
    function formatNumber(num) {
        if (num >= 10000) {
            return (num / 10000).toFixed(1) + '万';
        }
        return num.toString();
    }
    
    // 初始化页面加载动画（如果有）
    function initPageLoad() {
        // 隐藏加载动画
        const loader = document.getElementById('pageLoader');
        if (loader) {
            setTimeout(() => {
                loader.style.opacity = '0';
                setTimeout(() => {
                    loader.style.display = 'none';
                }, 300);
            }, 500);
        }
    }
    
    // 初始化页面
    initPageLoad();
    
    // 模拟用户操作的交互功能
    function initMockInteractions() {
        // 为所有按钮添加点击效果
        const buttons = document.querySelectorAll('button, .btn-primary, .btn-secondary');
        buttons.forEach(button => {
            button.addEventListener('click', function() {
                this.classList.add('scale-95');
                setTimeout(() => {
                    this.classList.remove('scale-95');
                }, 150);
            });
        });
    }
    
    initMockInteractions();
    
    // 为登录/注册按钮添加提示
    const loginButtons = document.querySelectorAll('a[href="login.html"]');
    const registerButtons = document.querySelectorAll('a[href="register.html"]');
    
    loginButtons.forEach(button => {
        if (button.textContent.includes('登录') || button.querySelector('.fa-sign-in')) {
            button.addEventListener('click', function(e) {
                // 在实际应用中，这里不应该阻止默认行为
                // 这里只是为了演示
                // e.preventDefault();
                // alert('跳转到登录页面');
            });
        }
    });
    
    registerButtons.forEach(button => {
        if (button.textContent.includes('注册') || button.querySelector('.fa-user-plus')) {
            button.addEventListener('click', function(e) {
                // 在实际应用中，这里不应该阻止默认行为
                // 这里只是为了演示
                // e.preventDefault();
                // alert('跳转到注册页面');
            });
        }
    });
    
    // 表单输入验证（简单版）
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        const requiredFields = form.querySelectorAll('[required]');
        
        form.addEventListener('submit', function(e) {
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('border-danger');
                    
                    // 添加错误提示
                    if (!field.nextElementSibling || !field.nextElementSibling.classList.contains('text-danger')) {
                        const errorText = document.createElement('p');
                        errorText.className = 'text-danger text-xs mt-1';
                        errorText.textContent = '此项为必填项';
                        field.parentNode.insertBefore(errorText, field.nextSibling);
                    }
                } else {
                    field.classList.remove('border-danger');
                    // 移除错误提示
                    if (field.nextElementSibling && field.nextElementSibling.classList.contains('text-danger')) {
                        field.nextElementSibling.remove();
                    }
                }
            });
            
            // 如果不是活动发布页面，这里不阻止默认提交
            // 在实际应用中，应该根据具体需求进行验证
            if (!form.id.includes('publishActivityForm') && !form.id.includes('contactForm') && !isValid) {
                e.preventDefault();
            }
        });
        
        // 输入时移除错误状态
        requiredFields.forEach(field => {
            field.addEventListener('input', function() {
                this.classList.remove('border-danger');
                if (this.nextElementSibling && this.nextElementSibling.classList.contains('text-danger')) {
                    this.nextElementSibling.remove();
                }
            });
        });
    });
    
    // 确保所有图片都有alt属性
    const images = document.querySelectorAll('img:not([alt])');
    images.forEach((img, index) => {
        img.alt = `图片${index + 1}`;
    });

    // 数字计数动画
    function animateCounter(element, target, duration = 2000) {
        const startTime = performance.now();
        const startValue = 0;
        
        function updateCounter(currentTime) {
            const elapsedTime = currentTime - startTime;
            if (elapsedTime < duration) {
                const progress = elapsedTime / duration;
                const currentValue = Math.floor(startValue + (target - startValue) * progress);
                element.textContent = new Intl.NumberFormat().format(currentValue);
                requestAnimationFrame(updateCounter);
            } else {
                element.textContent = new Intl.NumberFormat().format(target);
            }
        }
        
        requestAnimationFrame(updateCounter);
    }

    // 检测元素是否在视窗内
    function isInViewport(element) {
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }

    // 初始化图表
    const ctx = document.getElementById('activityChart');
    if (ctx) {
        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                datasets: [{
                    label: '活动数量',
                    data: [8, 12, 15, 20, 25, 30, 18, 15, 22, 28, 32, 25],
                    borderColor: '#165DFF',
                    backgroundColor: 'rgba(22, 93, 255, 0.1)',
                    tension: 0.4,
                    fill: true
                }, {
                    label: '参与人次',
                    data: [120, 180, 250, 380, 450, 580, 320, 280, 420, 550, 620, 480],
                    borderColor: '#0FC6C2',
                    backgroundColor: 'rgba(15, 198, 194, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    // 页面滚动动画
    const animateOnScroll = () => {
        const elements = document.querySelectorAll('.count-animation');
        elements.forEach(element => {
            if (isInViewport(element)) {
                const target = parseInt(element.textContent.replace(/,/g, ''));
                animateCounter(element, target);
                element.classList.add('animated');
            }
        });
    };

    // 初始检查
    animateOnScroll();
    
    // 滚动时检查
    window.addEventListener('scroll', animateOnScroll);

    // 表单验证
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            // 这里可以添加表单验证逻辑
            console.log('Form submitted:', form);
        });
    });

    // 收藏按钮交互
    const favoriteButtons = document.querySelectorAll('.fa-heart-o');
    favoriteButtons.forEach(button => {
        button.addEventListener('click', function() {
            this.classList.toggle('fa-heart-o');
            this.classList.toggle('fa-heart');
            this.classList.toggle('text-danger');
        });
    });

    // 移动端点击外部关闭菜单
    document.addEventListener('click', function(event) {
        if (mobileMenu && !mobileMenu.contains(event.target) && 
            mobileMenuBtn && !mobileMenuBtn.contains(event.target) &&
            !mobileMenu.classList.contains('hidden')) {
            mobileMenu.classList.add('hidden');
            const icon = mobileMenuBtn.querySelector('i');
            icon.classList.remove('fa-times');
            icon.classList.add('fa-bars');
        }
    });

    // 预加载图片
    const preloadImages = () => {
        const images = document.querySelectorAll('img[data-src]');
        images.forEach(img => {
            img.src = img.dataset.src;
            img.onload = () => {
                img.classList.add('loaded');
            };
        });
    };

    // 延迟加载图片
    if ('IntersectionObserver' in window) {
        const imgObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    if (img.dataset.src) {
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                        img.classList.add('loaded');
                    }
                    observer.unobserve(img);
                }
            });
        });

        document.querySelectorAll('img[data-src]').forEach(img => {
            imgObserver.observe(img);
        });
    } else {
        // 回退到传统加载方式
        preloadImages();
    }

    // 页面加载完成后的动画
    setTimeout(() => {
        document.body.classList.add('loaded');
    }, 300);
});

// 处理浏览器后退按钮
window.addEventListener('popstate', function() {
    // 这里可以添加后退按钮的处理逻辑
    console.log('Back button pressed');
});